<template>
	<view class="select-cat">
		<view v-if="false" class="head flex align-center justify-between">
			<view class="">
				<text>出发时间：</text>
				<text>{{ formData.start_time }}</text>
			</view>
			<!--  @click="selectDate" -->
			<view class="change-btn">
				<picker mode="date" :value="date" :start="startDate" :end="endTime ? endTime : endDate" @change="bindDateChange($event, 'start_time')">
					<text>重选</text>
				</picker>
			</view>
		</view>
		<view class="contaimer">
			<scroll-view scroll-y class="classify" :scroll-into-view="menuTo" scroll-with-animation>
				<view style="height: 100%;">
					<view class="bg-white">
						<view class="menu-item" :id="'menu'+index" :class="{'active-menu': current === index, 'active-menu-pre' : current > 0 && current - 1 === index, 'active-menu-next' : current < (lists.length - 1) && current + 1 === index}" v-for="(item, index) in lists" :key="index" @click="changeMenu(index)">
							<text>{{ item.type }}</text>
						</view>
					</view>
					<view class="bg-white">
						<view style="height: 200rpx;background-color: #f4f4f4;" :style="{'border-top-right-radius': current === lists.length - 1 ? '26rpx' : '0rpx'}"></view>
					</view>
				</view>
			</scroll-view>
			<scroll-view scroll-y class="lists" :scroll-into-view="into" scroll-with-animation :show-scrollbar="false" @scroll="handleScroll">
				<view style="height: 100%;">
					<view class="" v-for="(items, indexs) in lists" :key="indexs">
						<view :id="'id'+indexs" :data-viewTo="'menu'+indexs" :data-index="indexs" class="menu-content flex align-center justify-center">
							<view class="label">
								<text>{{ items.type }}</text>
							</view>
						</view>
						<view class="cat-list" v-for="(cat, idx) in items.data" :key="idx">
							<view class="flex-1 flex align-center padding-b24">
								<view v-if="cat.images && cat.images.length" class="image-wrap" @click="previewImg(cat.images)">
									<image :src="cat.images[0]" mode="aspectFill"></image>
								</view>
								<view class="">
									<view class="name text-overflow-hidden-2">
										<text>{{ cat.pinpai }}</text>
									</view>
									<view v-if="cat.pailiang || cat.zuoshu" class="sub">
										<text v-if="cat.pailiang" class="inline-block">{{ cat.pailiang }}</text>
										<text v-if="cat.zuoshu" class="inline-block">/{{ cat.zuoshu }}</text>
									</view>
								</view>
							</view>
							<view class="flex align-center justify-between footer-price-btn">
								<view v-if="cat.price" class="sub2">
									<text class="font-size-18">日均￥</text>
									<text>{{ cat.price }}</text>
								</view>
								<view style="width: 180rpx;" class="flex align-center justify-end">
									<view v-if="cat.quantity > 0 && cat.count > 0" class="count-wrap">
										<view class="btn" :class="{'disabled-btn' : cat.count === 0}" @click="subtract(cat)">
											<text class="iconfont">&#xe8cb;</text>
										</view>
										<view class="count">
											<text>{{ cat.count ? cat.count : 0 }}</text>
										</view>
										<view class="btn" :class="{'disabled-btn' : cat.count >= cat.quantity}" @click="add(cat)">
											<text class="iconfont">&#xe90b;</text>
										</view>
									</view>
									<view v-else-if="cat.quantity > 0" class="quantity" @click="add(cat)">
										<view class="quantity-num">
											<text>剩{{cat.quantity}}辆</text>
										</view>
										<view class="quantity-add-icon">
											<text class="iconfont icon-tianjia_huaban"></text>
										</view>
									</view>
									<view v-else class="add-btn" :class="{'disabled-add': cat.quantity === 0}" @click="add(cat)">
										<text>{{cat.quantity === null ? '加入订单' : (cat.quantity === 0 ? '无车' : `剩${cat.quantity}辆`) }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view style="height: 200rpx;"></view>
				</view>
			</scroll-view>
		</view>
		
		<view class="footer" :style="{'padding-bottom': safeAreaBottom ? safeAreaBottom+'px' : '24rpx'}">
			<view class="">
				<text>已选中</text>
				<text class="inline-block padding-8" style="color: #EA8135;">{{ total }}</text>
				<text>辆车</text>
			</view>
			<button class="sub-btn" :class="{'active-btn' : total}" :disabled="!total" @click="goContirm">
				<text>选好了</text>
			</button>
		</view>
		
		<!-- <datetime ref="datetime" @confirm="confirm($event, 'start_time')" :value="formData.start_time"></datetime> -->
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	import { previewImage } from '../../utils/uploadImg.js'
	
	export default {
		data() {
			return {
				data: '',
				total: 0,
				current: 0,
				lists: [],
				formData:{
					form_type: 1, // 表单类型
					car_reasons: '', // 用车事由
					applicant_name: '', // 申请人
					applicant_phone: '', // 联系电话
					car_destination: '', // 目的地
					start_time: '', // 出发时间
					end_time: '', // 还车时间
					car_data: [],
				},
				into: '',
				menuTo: '',
				scrollTimer: null,
				endTime: '',
				orderId: ''
			};
		},
		computed: {
			...mapState('common', ['safeAreaBottom']),
			
			startDate() {
			    return this.getDate('start');
			},
			endDate() {
			    return this.getDate('end');
			}
		},
		onLoad(options) {
			if (options.formData) {
				this.formData = JSON.parse(decodeURIComponent(options.formData))
			}
			this.orderId = options.orderId || ''
			this.endTime = this.$formatTime(this.formData.end_time, 'YYYY-MM-DD')
			this.getLists()
		},
		methods:{
			previewImg(list) {
				previewImage(list, 0)
			},
			// 获取详情
			getInfo() {
				this.$api.orderDetailsApi({
					id: this.orderId
				}).then(res => {
					const start = res.data.start_time.split(' ');
					let end = []
					if (res.data.end_time) {
						end = res.data.end_time.split(' ');
					}
					const startArr = start[1].split(':')
					let endArr = []
					if (end.length) {
						endArr = end[1].split(':')
					}
					this.times = {
						time1: `${startArr[0]}:${startArr[1]}`,
						time2: endArr.length ? `${endArr[0]}:${endArr[1]}` : ''
					}
					this.formData = {
						id: this.orderId,
						form_type: res.data.form_type,
						car_reasons: res.data.car_reasons, // 用车事由
						applicant_name: res.data.applicant_name, // 申请人
						applicant_phone: res.data.applicant_phone, // 联系电话
						car_destination: res.data.car_destination, // 目的地
						start_time: start[0], // 出发时间
						end_time: end[0], // 还车时间
						car_data: res.data.car_data,
					}
					
					if (this.formData.car_data && this.formData.car_data.length) {
						for (let i = 0; i < this.lists.length; i++) {
							const items = this.lists[i]
							for (let j = 0; j < items.data.length; j++) {
								let item = items.data[j]
								const index = this.formData.car_data.findIndex(el=> el.pinpai === item.pinpai)
								if (index !== -1) {
									item.count = this.formData.car_data[index].count
									item.is_driver = this.formData.car_data[index].is_driver
								}
							}
						}
					}
					this.computeTotal()
					
				}).catch(err => {
					console.log(err);
				})
			},
			getLists() {
				this.$api.catListApi().then(res=> {
					this.lists = res.data
					if (this.orderId) {
						this.getInfo()
					}
					
					this.$forceUpdate()
				}).catch(err=>{
					console.log(err);
				})
			},
			// 切换分类
			changeMenu(index) {
				this.current = index
				this.into = `id${index}`
			},
			// 滚动
			handleScroll(event) {
				// if(this.scrollTimer != null){
				// 	clearTimeout(this.scrollTimer);
				// }
				// this.scrollTimer = setTimeout(()=>{this.getIndex();}, 100);
				this.getIndex()
			},
			getIndex() {
				const query = uni.createSelectorQuery()
				query.selectAll('.menu-content').boundingClientRect()
				query.selectViewport().scrollOffset()
				query.exec((res) => {
					const lists = res[0];
					for (let i = 0; i < lists.length; i++) {
						const item = lists[i]
						if (item.top >= 0 && item.top < 60) {
							this.menuTo = item.dataset.viewto
							this.current = item.dataset.index
							break ;
						}
					}
				});
			},
			// 前往确认订单
			goContirm() {
				const lists = []
				for (let i = 0; i < this.lists.length; i++) {
					const items = this.lists[i]
					for (let j = 0; j < items.data.length; j++) {
						const item = items.data[j]
						if (item.count) {
							item.is_driver = 0
							lists.push(item)
						}
					}
				}
				this.formData.car_data = lists
				uni.navigateTo({
					url: '/pages/application-form/application-form?formData=' + encodeURIComponent(JSON.stringify(this.formData)) + '&orderId=' + this.orderId
					// url: '/pages/confirm/confirm?formData=' + encodeURIComponent(JSON.stringify(this.formData))
				})
			},
			// 选择时间
			selectDate() {
				this.$refs.datetime.open()
			},
			// 减
			subtract(item) {
				if (item.count >= 1) {
					item.count--
				}
				this.computeTotal()
				this.$forceUpdate()
			},
			// 加
			add(item) {
				if(item.quantity == 0 || item.count >= item.quantity) { 
					uni.showToast({
						icon: 'none',
						title: '已到达最大添加数量'
					})
					return 
				}
				if (item.count === undefined) {
					item.count = 0
				}
				item.count++
				this.computeTotal()
				this.$forceUpdate()
			},
			// 计算总数
			computeTotal() {
				let total = 0
				for (let i = 0; i < this.lists.length; i++) {
					const items = this.lists[i]
					for (let j = 0; j < items.data.length; j++) {
						const cat = items.data[j]
						if (cat.count) {
							total+=cat.count
						}
					}
				}
				this.total = total
			},
			// 选择时间
			bindDateChange(event) {
				const { value } = event.detail
				this.formData.start_time = `${value} 00:00:00`
				this.getLists()
			},
			// 选择时间 -- 后期删除
			confirm(res, type) {
				this.formData[type] = res[0]+'-'+res[1]+'-'+res[2]+' '+res[3]+':'+res[4]+':'+res[5];
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.select-cat{
		flex: 1;
		width: 100%;
		height: 100%;
		display: flex;
		box-sizing: border-box;
		flex-direction: column;
		
		.head{
			font-size: 28rpx;
			padding: 24rpx 32rpx;
			background-color: #a5daf5;
			
			.change-btn{
				width: 100rpx;
				height: 52rpx;
				display: flex;
				color: #FFFFFF;
				line-height: 1;
				align-items: center;
				border-radius: 100rpx;
				justify-content: center;
				background-color: rgba(0, 82, 217, 0.1);
			}
		}
		
		.contaimer{
			width: 100%;
			flex: 1;
			overflow: hidden;
			display: flex;
			box-sizing: border-box;
		}
		
		.classify{
			width: 200rpx;
			height: 100%;
			background-color: #f4f4f4;
			
			.menu-item{
				height: 100rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 26rpx;
				font-weight: 600;
				text-align: center;
				background-color: #f4f4f4;
			}
			
			.active-menu{
				background-color: #FFFFFF;
			}
			
			.active-menu-pre {
				border-bottom-right-radius: 26rpx;
			}
			
			.active-menu-next{
				border-top-right-radius: 26rpx;
			}
		}
		
		.lists{
			flex: 1;
			height: 100%;
			box-sizing: border-box;
			background-color: #FFFFFF;
		}
		
		.label{
			position: relative;
			padding: 24rpx;
			font-size: 28rpx;
			display: flex;
			align-items: center;
			color: #999999;
			
			&::before{
				position: absolute;
				content: '';
				right: 102%;
				width: 100rpx;
				height: 1rpx;
				background-color: #dedede;
			}
			&::after{
				position: absolute;
				content: '';
				left: 102%;
				width: 100rpx;
				height: 1rpx;
				background-color: #dedede;
			}
		}
		
		.cat-list{
			position: relative;
			margin: 0 24rpx;
			margin-bottom: 24rpx;
			padding: 24rpx ;
			border-radius: 12rpx;
			overflow: hidden;
			box-sizing: border-box;
			background-color: #FFFFFF;
			border-bottom: 1rpx solid #eee;
			box-shadow: 0px 8rpx 22rpx rgba(0, 0, 0, 0.1);
			// box-shadow: 0rpx 0rpx 33rpx rgba(0, 0, 0, 0.1);
			
			.image-wrap{
				aspect-ratio: 4 / 3;
				width: auto;
				height: 126rpx;
				overflow: hidden;
				flex-shrink: 0;
				margin-right: 24rpx;
				border-radius: 8rpx;
				// border: 1px dashed #999;
				
				image{
					width: 100%;
					height: 100%;
				}
			}
			
			.name{
				color: #000000;
				font-size: 34rpx;
				font-weight: 600;
			}
			
			.sub{
				color: #999999;
				font-size: 24rpx;
				padding-top: 16rpx;
			}
			
			.sub2{
				color: #EA8135;
				font-size: 24rpx;
			}
			
		}
		
		.footer-price-btn{
			padding-top: 16rpx;
			border-top: 1rpx solid #f4f4f4;
		}
		
		.quantity{
			display: flex;
			align-items: center;
			border-radius: 8rpx;
			overflow: hidden;
			background-color: rgba(0, 82, 217, 0.2);
		}
		
		.quantity-num {
			display: flex;
			height: 44rpx;
			font-size: 18rpx;
			padding: 8rpx 24rpx;
			align-items: center;
			box-sizing: border-box;
			justify-content: center;
			color: var(--primary-color);
		}
		
		.quantity-add-icon{
			display: flex;
			height: 44rpx;
			width: 44rpx;
			color: #FFFFFF;
			font-weight: 600;
			align-items: center;
			justify-content: center;
			background-color: #EA8135;
			
			.icon-tianjia_huaban{
				font-size: 26rpx;
			}
		}
		
		.add-btn{
			flex-shrink: 0;
			font-size: 20rpx;
			margin-left: 40rpx;
			padding: 8rpx 16rpx;
			border-radius: 100rpx;
			color: var(--primary-color);
			background-color: rgba(0, 82, 217, 0.1);
		}
		
		.disabled-add {
			color: #999999;
			background-color: #e5e5e5 !important;
		}
		
		.count-wrap{
			width: 140rpx;
			display: flex;
			align-items: center;
			border-radius: 100rpx;
			border: 1rpx solid #dedede;
			justify-content: space-between;
			
			.count{
				font-size: 28rpx;
			}
			
			.btn{
				display: flex;
				padding: 6rpx;
				
				.iconfont{
					font-size: 36rpx;
				}
			}
			
			.disabled-btn{
				color: #999999;
			}
		}
		
		.footer{
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			width: 100%;
			z-index: 9;
			display: flex;
			color: #000000;
			font-size: 28rpx;
			align-items: center;
			padding: 24rpx 32rpx;
			box-sizing: border-box;
			background-color: #FFFFFF;
			justify-content: space-between;
			box-shadow: 0rpx 0rpx 22rpx rgba(0, 0, 0, 0.1);
			
			.sub-btn{
				margin: 0; 
				height: 72rpx;
				display: flex;
				color: #FFFFFF;
				line-height: 1;
				font-size: 32rpx;
				align-items: center;
				padding: 12rpx 32rpx;
				border-radius: 12rpx;
				justify-content: center;
				background-color: rgba(0, 0, 0, 0.3);
				
				&::after{
					border: none;
				}
			}
			
			.active-btn{
				color: var(--primary-color);
				background-color: rgba(0, 82, 217, 0.1);
			}
		}
	}
</style>
